<template>
  <el-image
    :src="imageUrl"
    :preview-src-list="getPreviewList"
    :style="style"
    preview-teleported
    class="imager text-center"
    @click="handleClick"
  >
    <template #placeholder>
      <div class="imager-slot">
        <i class="i-ep-loading"></i>
      </div>
    </template>
    <template #error>
      <div class="imager-slot" @click="handleClick">
        <i class="i-ep-picture-rounded"></i>
      </div>
    </template>
  </el-image>
</template>

<script setup lang="ts">
  import { getImage } from '#/utils/image'

  defineOptions({
    name: 'Imager',
  })

  const props = withDefaults(
    defineProps<{
      height?: number
      model?: string
      preview?: boolean
      routeName?: string
      routeParams?: object
      url: string
      width?: number
    }>(),
    {
      model: 'default',
      width: 80,
      height: 80,
      preview: true,
      routeName: '',
      routeParams: () => ({}),
    }
  )

  const emits = defineEmits<{
    (e: 'on-click'): void
  }>()

  const config = computed(() => {
    // 宽、高都不指定，返回原图
    if (props.width === 0 && props.height === 0) {
      return {}
    }

    // 正方形
    if (props.model === 'square') {
      return { model: 'crop', width: props.width * 2, height: props.getHeight * 2 }
    }

    // 仅指定高度
    if (props.width === 0 && props.height !== 0) {
      return { height: props.height * 2 }
    }

    // 仅指定宽度
    if (props.width !== 0 && props.height === 0) {
      return { width: props.width * 2 }
    }

    // 七牛按指定的尺寸读取时，画质有点模糊，所以 * 2
    return { model: props.model, width: props.width * 2, height: props.height * 2 }
  })

  const getHeight = computed(() => {
    return props.height == 0 ? props.width : props.height
  })

  const imageUrl = computed(() => props.url || getImage(props.url, config))

  const getPreviewList = computed(() => {
    if (!props.preview) return []

    return [props.url]
  })

  const style = computed(() => {
    const ms = '96px'
    // 宽、高都不指定，返回原图
    if (props.width === 0 && props.height === 0) {
      return { minWidth: ms, minHeight: ms, lineHeight: ms }
    }

    // 正方形
    if (props.model === 'square') {
      return {
        width: `${props.width}px`,
        height: `${getHeight}px`,
        lineHeight: `${getHeight}px`,
      }
    }

    // 仅指定高度
    if (props.width === 0 && props.height !== 0) {
      return { height: `${props.height}px`, lineHeight: `${props.height}px` }
    }

    // 仅指定宽度
    if (props.width !== 0 && props.height === 0) {
      return { width: `${props.width}px` }
    }

    return {
      width: `${props.width}px`,
      height: `${props.height}px`,
      lineHeight: `${props.height}px`,
    }
  })

  const handleClick = () => {
    if (!props.preview) {
      emits('on-click')
    }
  }
</script>
